package com.yxq.mdt.app.modules.order.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.logistics.ui.LogisticsActivity;
import com.yxq.mdt.app.modules.order.bean.EventOrderMsg;
import com.yxq.mdt.app.modules.order.bean.ExpressBean;
import com.yxq.mdt.app.modules.order.bean.OrderConfirmBean;
import com.yxq.mdt.app.modules.order.bean.OrderDetailBean;
import com.yxq.mdt.app.modules.order.bean.OrderListBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultBalanceBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultWxBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitResult;
import com.yxq.mdt.app.modules.order.model.OrderModel;
import com.yxq.mdt.app.modules.order.model.OrderStatusUtils;
import com.yxq.mdt.app.modules.order.prestener.IOrderContract;
import com.yxq.mdt.app.modules.order.prestener.OrderPresenter;
import com.yxq.mdt.app.modules.order.ui.adapter.OrderDetailGoodsListAdapter;
import com.yxq.mdt.app.modules.personal.ui.activity.MainPersonalOrderAfterAc;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author L
 * @time
 * @describe 订单详情
 */
public class OrderDetailActivity extends BaseActivity<OrderPresenter> implements IOrderContract.View {


    @BindView(R.id.order_detail_tv_status)
    TextView orderDetailTvStatus;
    @BindView(R.id.address_tv_name)
    TextView addressTvName;
    @BindView(R.id.address_tv_phone)
    TextView addressTvPhone;
    @BindView(R.id.address_tv_address)
    TextView addressTvAddress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.order_tv_number)
    TextView orderTvNumber;
    @BindView(R.id.order_tv_copy)
    TextView orderTvCopy;
    @BindView(R.id.order_tv_date)
    TextView orderTvDate;
    @BindView(R.id.order_detail_tv_all_price)
    TextView orderDetailTvAllPrice;
    @BindView(R.id.order_detail_tv_all_num)
    TextView orderDetailTvAllNum;
    @BindView(R.id.order_detail_tv_all_delivery)
    TextView orderDetailTvAllDelivery;
    @BindView(R.id.order_tv_all_price)
    TextView orderTvAllPrice;
    @BindView(R.id.order_list_layout_button)
    LinearLayout orderListLayoutButton;
    @BindView(R.id.order_detail_tv_all_price_hint)
    TextView orderDetailTvAllPriceHint;
    @BindView(R.id.order_detail_tv_all_num_hint)
    TextView orderDetailTvAllNumHint;
    @BindView(R.id.order_detail_tv_all_delivery_hint)
    TextView orderDetailTvAllDeliveryHint;
    @BindView(R.id.order_list_tv_button_1)
    TextView orderListTvButton1;
    @BindView(R.id.order_list_tv_button_2)
    TextView orderListTvButton2;
    @BindView(R.id.order_list_tv_button_3)
    TextView orderListTvButton3;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.order_detail_tv_yh_price_hint)
    TextView orderDetailTvYhPriceHint;
    @BindView(R.id.order_detail_tv_yh_price)
    TextView orderDetailTvYhPrice;
    @BindView(R.id.order_detail_layout_yh_price)
    RelativeLayout orderDetailLayoutYhPrice;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    public void initView() {
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.detail(getIntent().getStringExtra("orderId")));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new OrderPresenter(this, new OrderModel());
    }

    private void refresh() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }

    @Override
    public void onLoadSuccess(OrderConfirmBean orderConfirmBean) {

    }

    @Override
    public void onLoadFailed(String err) {

    }

    @Override
    public void onLoadListSuccess(OrderListBean orderListBean) {

    }

    @Override
    public void onLoadListFailed(String err) {

    }

    @Override
    public void onSubmitSuccess(OrderSubmitResult orderSubmitResult) {

    }

    @Override
    public void onSubmitFailed(String err) {

    }

    @Override
    public void onPayBalanceSuccess(OrderPayResultBalanceBean orderPayResultBalanceBean) {

    }

    @Override
    public void onPayBalanceFailed(String err) {

    }

    @Override
    public void onPayWxSuccess(OrderPayResultWxBean orderPayResultWxBean) {

    }

    @Override
    public void onPayWxFailed(String err) {

    }

    @Override
    public void onDetailSuccess(OrderDetailBean orderDetailBean) {
        refreshLayout.finishRefresh();
        bindUI(orderDetailBean);
    }

    /**
     * 填充数据到界面
     *
     * @param orderDetailBean
     */
    private void bindUI(OrderDetailBean orderDetailBean) {
        //订单信息
        orderDetailTvStatus.setText(orderDetailBean.getStatus());
        addressTvName.setText(orderDetailBean.getName());
        addressTvPhone.setText(orderDetailBean.getMobile());
        addressTvAddress.setText(orderDetailBean.getAddress());
        orderTvNumber.setText("订单编号：" + orderDetailBean.getOrder_no());
        orderTvDate.setText("下单时间：" + orderDetailBean.getAddtime());
        orderTvAllPrice.setText(String.format("￥%.2f", orderDetailBean.getPay_price()));//总计
        orderDetailTvAllPrice.setText(String.format("￥%.2f", orderDetailBean.getGoods_total_price()));//商品总额
        orderDetailTvAllNum.setText("x" + orderDetailBean.getNum());
        orderDetailTvAllDelivery.setText(String.format("￥%.2f", orderDetailBean.getExpress_price()));
        orderTvCopy.setOnClickListener(view -> {
            if (TextUtils.isEmpty(orderDetailBean.getOrder_no())) {
                ToastUtils.showShort("没有订单编号");
                return;
            }
            StringUtils.copy(mActivity, orderDetailBean.getOrder_no());
            ToastUtils.showShort("复制成功");
        });
        if (!TextUtils.isEmpty(orderDetailBean.getBefore_update())) {
            orderDetailLayoutYhPrice.setVisibility(View.VISIBLE);
            orderDetailTvYhPriceHint.setText(orderDetailBean.getBefore_update());
            orderDetailTvYhPrice.setText(String.format("￥%.2f", orderDetailBean.getMoney()));
        } else {
            orderDetailLayoutYhPrice.setVisibility(View.GONE);
        }
        //购买的商品列表
        OrderDetailGoodsListAdapter orderDetailGoodsListAdapter = new OrderDetailGoodsListAdapter(R.layout.layout_order_detail_goods_item_layout, orderDetailBean.getGoods_list());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(orderDetailGoodsListAdapter);
        orderDetailGoodsListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转商品详情
                Bundle bundle = new Bundle();
                bundle.putString("id", orderDetailGoodsListAdapter.getItem(position).getGoods_id() + "");
                IntentHelper.arouterUri(RouteTable.ROUTER_ACTIVITY_GOODS_DETAIL, bundle);
            }
        });
        orderDetailGoodsListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_refund://申请售后
                        Intent intent = new Intent(mActivity, MainPersonalOrderAfterAc.class);
                        intent.putExtra("orderId", orderDetailGoodsListAdapter.getItem(position).getOrder_detail_id());
                        startActivity(intent);
                        break;
                }
            }
        });
        //订单状态
        String status = OrderStatusUtils.status(orderDetailBean.getIs_pay(), orderDetailBean.getIs_send(), orderDetailBean.getIs_confirm(), orderDetailBean.getIs_comment(), orderDetailBean.getApply_delete());

        //设置按钮状态
        switch (status) {
            case "待付款":
                orderListLayoutButton.setVisibility(View.VISIBLE);
                orderListTvButton1.setVisibility(View.VISIBLE);
                orderListTvButton2.setVisibility(View.GONE);
                orderListTvButton3.setVisibility(View.VISIBLE);

                orderListTvButton1.setText("取消订单");
                orderListTvButton3.setText("立即付款");

                orderListTvButton1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //取消订单
                        OrderModel.revoke(orderDetailBean.getOrder_id(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                EventBus.getDefault().post(new EventOrderMsg(1));
                                ToastUtils.showShort(s);
                                refresh();
                            }

                            @Override
                            public void onError(String errMsg) {
                                ToastUtils.showShort(errMsg);
                            }
                        });
                    }
                });
                orderListTvButton3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //跳转支付
                        Intent intent = new Intent(mActivity, OrderPayActivity.class);
                        intent.putExtra("orderId", orderDetailBean.getOrder_id());
                        intent.putExtra("price", String.format("%.2f", orderDetailBean.getPay_price()));
                        startActivity(intent);
                    }
                });
                break;
            case "待发货":
                orderListTvButton1.setVisibility(View.GONE);
                orderListTvButton2.setVisibility(View.GONE);
                orderListTvButton3.setVisibility(View.GONE);
                if (orderDetailBean.getApply_delete() == 1) {
                    orderListLayoutButton.setVisibility(View.GONE);
                    orderListTvButton3.setVisibility(View.GONE);
                } else {
                    orderListLayoutButton.setVisibility(View.VISIBLE);
                    orderListTvButton1.setVisibility(View.VISIBLE);
                    orderListTvButton1.setText("申请退款");
                    orderListTvButton1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //申请退款
                            CostumerDialog dialog = new CostumerDialog.Builder(mActivity, R.style.custom_dialog_no_match)
                                    .setContentView(R.layout.dialog_clear_cache_layout)
                                    .setCancelable(true)
                                    .create();

                            TextView title = dialog.findViewById(R.id.tv_title);

                            title.setText("");

                            TextView content = dialog.findViewById(R.id.tv_content);
                            content.setText("确定申请退款？");

                            //继续
                            TextView sure = dialog.findViewById(R.id.tv_sure);
                            sure.setText("确定");
                            sure.setOnClickListener(v -> {
                                dialog.dismiss();
                                OrderModel.revoke(orderDetailBean.getOrder_id(), new ApiModel.CommonCallback<String>() {
                                    @Override
                                    public void onSuccess(String s) {
                                        ToastUtils.showShort("已提交");
                                        refresh();
                                        EventBus.getDefault().post(new EventOrderMsg(2));
                                    }

                                    @Override
                                    public void onError(String errMsg) {
                                        ToastUtils.showShort(errMsg);
                                    }
                                });
                            });

                            //取消
                            TextView cancel = dialog.findViewById(R.id.tv_cancel);
                            cancel.setText("取消");
                            cancel.setOnClickListener(v -> {
                                dialog.dismiss();
                            });

                            dialog.show();

                        }
                    });
                }
                break;
            case "退款":
                orderListLayoutButton.setVisibility(View.VISIBLE);
                orderListTvButton3.setVisibility(View.VISIBLE);
                orderListTvButton1.setVisibility(View.GONE);
                orderListTvButton2.setVisibility(View.GONE);
                orderListTvButton3.setText("申请退款中");
                orderListTvButton3.setBackgroundResource(R.drawable.shape_btn_gray_bg);
                orderListTvButton3.setOnClickListener(null);
                break;
            case "待收货":
                orderListLayoutButton.setVisibility(View.VISIBLE);
                orderListTvButton1.setVisibility(View.GONE);
                orderListTvButton2.setVisibility(View.VISIBLE);
                orderListTvButton3.setVisibility(View.VISIBLE);

                orderListTvButton2.setText("查看物流");
                orderListTvButton3.setText("确认收货");

                orderListTvButton2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //物流
                        Intent intent = new Intent(mActivity, LogisticsActivity.class);
                        intent.putExtra("orderId", orderDetailBean.getOrder_id());
                        intent.putExtra("orderType", 1);
                        startActivity(intent);
                    }
                });
                orderListTvButton3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //确认收货
                        OrderModel.confirm(orderDetailBean.getOrder_id(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                ToastUtils.showShort(s);
                                EventBus.getDefault().post(new EventOrderMsg(3));
                                EventBus.getDefault().post(new EventOrderMsg(4));
                                refresh();
                            }

                            @Override
                            public void onError(String errMsg) {
                                ToastUtils.showShort(errMsg);
                            }
                        });
                    }
                });
                break;
            case "待评价":
//                //特殊处理订单已完成状态
//                if ("订单已完成".equals(orderDetailBean.getStatus())) {
//                    orderListLayoutButton.setVisibility(View.GONE);
//                    orderListTvButton1.setVisibility(View.GONE);
//                    orderListTvButton2.setVisibility(View.GONE);
//                    orderListTvButton3.setVisibility(View.GONE);
//                    return;
//                }
                orderListLayoutButton.setVisibility(View.VISIBLE);
                orderListTvButton1.setVisibility(View.GONE);
                orderListTvButton2.setVisibility(View.GONE);
                orderListTvButton3.setVisibility(View.VISIBLE);

                orderListTvButton3.setText("立即评价");

                orderListTvButton3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //跳转订单评价页面
                        Intent intent = new Intent(mActivity, OrderCommentActivity.class);
                        intent.putExtra("orderId", orderDetailBean.getOrder_id());
                        startActivity(intent);
                    }
                });
                break;
            case "已完成":
                orderListLayoutButton.setVisibility(View.GONE);
                orderListTvButton1.setVisibility(View.GONE);
                orderListTvButton2.setVisibility(View.GONE);
                orderListTvButton3.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onDetailFailed(String err) {
        refreshLayout.finishRefresh();
        ToastUtils.showShort(err);
        if ("订单不存在".equals(err)) {
            finish();
        }
    }

    @Override
    public void onExpressSuccess(ExpressBean expressBean) {

    }

    @Override
    public void onExpressFailed(String err) {

    }

}
